<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/9/16
 * Time: 15:36
 */

namespace app\admin\controller;


use app\model\CustomerModel;
use app\model\OrderModel;
use app\model\OrderSonModel;
use app\model\UserModel;
use cmf\controller\AdminBaseController;
use think\Db;
use think\db\Query;
use think\Exception;
use think\Validate;

/**
 * Class OrderController
 * @package app\admin\controller
 * 后台订单模块
 */
class OrderController extends AdminBaseController
{
    protected $arrWhere = [];
    protected  $admin_name = '';

    public function _initialize()
    {
        $this->admin_name = UserModel::where('id',session('ADMIN_ID'))->value('user_login');
    }

    /**
     * @return \think\response\View
     * 订单列表
     */
    public function order_list()
    {
        $data = $this->request->param();
        $order_list = OrderModel::where(function (Query $query) {
            //手机号模糊搜索
            $data = $this->request->param();
            if (!empty($data['phone'])) {
                $phone = trim($data['phone']);
                $ids = CustomerModel::where('phone', 'like',"%$phone%")->column('id');
                $query->where('user_id', 'in',$ids);
            }
            //相关人员
            if(!empty($data['name'])){
                $user_id = Db::name('user')->where('user_login',$data['name'])->value('id');
                if(!empty($user_id)){
                    $query->where('about','=',$user_id)->whereOr('lawyer','=',$user_id);
                }else{
                    $query->where('id','=',null);
                }
            }
            //地区筛选
            if (!empty($data['province'])) {
                $province = trim($data['province']);
                $this->arrWhere['province'] = ['like','%'.$province.'%'];
            }
            if (!empty($data['city'])) {
                $city = trim($data['city']);
                $this->arrWhere['city'] = ['like','%'.$city.'%'];
            }
            if (!empty($data['area'])) {
                $area = trim($data['area']);
                $this->arrWhere['area'] = ['like','%'.$area.'%'];
            }
            $user_ids = CustomerModel::where($this->arrWhere)->column('id');
            $query->where('user_id', 'in',$user_ids);
            //订单类型
            if(!empty($data['order_type'])){
                $query->where('order_type',$data['order_type']);
            }
            //时间筛选
            if(!empty($data['create_time'])){
                $create_time = strtotime($data['create_time']);
                $query->where('create_time','>=',$create_time);
            }
            if(!empty($data['end_time'])){
                $end_time = strtotime($data['end_time']);
                $query->where('create_time','<=',$end_time);
            }
            //状态筛选
            if(!empty($data['status'])){
                $status = $data['status'];
                $query->where('status','=',$status);
            }

        })->with(['getUser'=>function($query){
            $query->field('id,name,phone,province,city,area');
        }])->with(['getAbout'=>function($query1){
            $query1->field('id,user_login');
        }])->with(['getLawyer'=>function($query2){
            $query2->field('id,user_login');
        }])->paginate(10);
		
     	 $order_list->appends($data);
        $page = $order_list->render();

        //判断用户是否拖欠尾款
        $order_list = $order_list->toArray();
        foreach ($order_list['data'] as $k=>$v){
            if($v['status']=='案件完结'){
                    if(intval((time()-$v['update_time'])/86400)>3){
                        $order_list['data'][$k]['status'] = '拖欠尾款';
                        $arr['status'] = '拖欠尾款';
                        $arr['update_time'] = time();
                        //更新父订单状态和用户状态为拖欠尾款
                        Db::name('order')->where('order_no',$v['order_no'])->update($arr);
                        Db::name('customer')->where('id',$v['get_user']['id'])->update($arr);

                }
            }
        }
        if(!empty($data['status'])){
            $status = $data['status'];
        }else{
            $status = '';
        }
        if(!empty($data['order_type'])){
            $order_type = $data['order_type'];
        }else{
            $order_type = '';
        }
        return view('',['list'=>$order_list['data'],'page'=>$page,'data'=>$data,'status'=>$status,'order_type'=>$order_type]);
    }


    /**
     * 订单详情
     * order_no     订单号
     */
    public function order_details()
    {
        $order_no = request()->param('order_no');
        $order_details = OrderModel::where('order_no',$order_no)->with(['getUser'=>function($query){
            $query->field('id,name,phone,province,city,area');
        }])->with(['getAbout'=>function($query1){
            $query1->field('id,user_login');
        }])->with(['getLawyer'=>function($query2){
            $query2->field('id,user_login');
        }])->select();

        $order_son = OrderSonModel::where('parent_order',$order_no)->select();
        return view('',['list'=>$order_details,'order_son'=>$order_son,'order_no'=>$order_no]);
    }



    /**
     * 勾单|取消订单
     * order_no      订单号
     * type          类型 2为取消订单| 1为勾单
     * user_id       用户id
     * status       当前订单状态
	 * admin_name   勾单人
     */
    public function hook_sheet()
    {
        $validate = new Validate([
            'order_no'=>'require',
            'type'  => 'require',
        ]);
        $validate->message([
            'user_id.require' => '用户id不能为空',
            'order_no.require' => '订单号不能为空',
        ]);

        $post = request()->param();
        if (!$validate->check($post)) {
            return_json(0,$validate->getError());
        }
        /**
         * 开启事务
         */
        Db::startTrans();
        try{
            if($post['type']==1){
                if($post['admin_name'] !== $this->admin_name){
                    return_json(0,'勾单人与当前操作者不符合!');
                }
                //根据不同的订单状态更改用户状态和订单状态
                if($post['status']=='首款待支付'){
                    $data['status'] = '待指派';
                    $user_status = '成交';
                    $order_type = 1;
                }else{
                    $data['status'] = '完成';
                    $user_status = '完成';
                    $order_type = 2;
                }

                $res1 = Db::name('customer')->where('id',$post['user_id'])->update(['status'=>$user_status,'update_time'=>time(),'lawyer_id'=>'']);
                //插入用户状态记录
                $record_data['user_id'] = $post['user_id'];
                $record_data['type_name'] = $user_status;
                $record_data['feedback'] = '后台勾单';
                //获取订单发起人id
                $admin_id = Db::name('order')->where('order_no',$post['order_no'])->value('admin_id');
                $admin_name = Db::name('user')->where('id',$admin_id)->value('user_login');
                $record_data['content'] = date('Y-m-d H:i:s').','.$admin_name.','.$record_data['feedback'];
                $record_data['admin_id'] = session('ADMIN_ID');
                $record_data['create_time'] = time();
                $res4 = Db::name('record')->insert($record_data);

                $res3 = Db::name('order_son')->where('parent_order',$post['order_no'])->where('order_type',$order_type)->update(['status'=>'已支付','remarks'=>'勾单人:'.$post['admin_name'],'pay_time'=>time()]);
                //更改父订单状态|插入订单操作状态记录
                $res2 = $this->order_operation($post['order_no'],$data,'勾单');
                if($res1 && $res2 && $res3 &&$res4){
                    Db::commit();
                    return_json(1,'操作成功');
                }else{
                    /**
                     * 事务回滚
                     */
                    Db::rollback();
                    return_json(0,'操作失败');
                }
            }else{
                //删除父订单以及子订单
                $res1 = Db::name('order')->where('order_no',$post['order_no'])->delete();
                $res2 = Db::name('order_son')->where('parent_order',$post['order_no'])->delete();
                if($res1 && $res2){
                    Db::commit();
                    return_json(1,'操作成功');
                }else{
                    /**
                     * 事务回滚
                     */
                    Db::rollback();
                    return_json(0,'操作失败');
                }
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,$e->getMessage());
        }
    }


    /**
     * 指派律师|更换律师
     * lawyer_id     律师id
     * order_no      订单号
     * user_id       用户id
     */
    public function appointed_lawyer()
    {
        $validate = new Validate([
            'lawyer_id'=>'require',
            'order_no'  => 'require',
        ]);
        $validate->message([
            'lawyer_id.require' => '律师id不能为空',
            'order_no.require' => '订单号不能为空',
        ]);

        $post = request()->param();
        if (!$validate->check($post)) {
            return_json(0,$validate->getError());
        }
        
        $data['status'] = '正在办案';
        $data['lawyer'] = $post['lawyer_id'];
        /**
         * 开启事务
         */
        Db::startTrans();
        try{
        	$order_details = Db::name('order')->where('order_no',$post['order_no'])->find();
        	//判断是指派还是更换律师
        	if(empty($order_details['lawyer'])){
        		$res = $this->order_operation($post['order_no'],$data,'指派律师');
            //将用户状态改为办案中|将律师绑定到用户表
	            $user_res = Db::name('customer')->where('id',$post['user_id'])->update(['status'=>'办案中','lawyer_id'=>$post['lawyer_id']]);
	            if($res && $user_res){
	                Db::commit();
	                return_json(1,'操作成功');
	            }else{
	                Db::rollback();
	                return_json(0,'操作失败');
	            }
        	}else{
        		//更换用户律师
        		$user_res = Db::name('customer')->where('id',$post['user_id'])->update(['lawyer_id'=>$post['lawyer_id']]);
        		$order_status = Db::name('order_operation')->where('order_no',$post['order_no'])->order('create_time desc')->value('order_status');
        		
        		//插入订单操作记录
        		$res = Db::name('order_operation')->insert([
		            'order_no'=>$post['order_no'],
		            'admin_id'=>session('ADMIN_ID'),
		            'operation'=>'更换律师',
		            'order_status'=>$order_status,
		            'create_time'=>time(),
		            'type'=>2,
		        ]);
		        //更改订单律师
		        $res1 = Db::name('order')->where('order_no',$post['order_no'])->update(['lawyer'=>$post['lawyer_id']]);
		        if($res && $user_res && $res1){
	                Db::commit();
	                return_json(1,'操作成功');
	            }else{
	                Db::rollback();
	                return_json(0,'操作失败');
	            }
        	}
        	
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,$e->getMessage());
        }

    }


    /**
     * 确认案情
     * order_no      订单号
     */
    public function confirm_case()
    {
        $order_no = request()->param('order_no');
        $data['status'] = '整理证据';
        Db::startTrans();
        try{
            $res = $this->order_operation($order_no,$data,'确认案情');
            if($res){
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,$e->getMessage());
        }
    }

    /**
     * 整理完成
     * file_number   档案号
     * order_no      订单号
     * user_id       用户id
     */
    public function finishing()
    {
        $validate = new Validate([
            'file_number'=>'require',
            'order_no'  => 'require',
            'user_id'  => 'require',
        ]);
        $validate->message([
            'file_number.require' => '档案号不能为空',
            'order_no.require' => '订单号不能为空',
            'user_id.require' => '用户id为空',
        ]);

        $post = request()->param();
        if (!$validate->check($post)) {
            return_json(0,$validate->getError());
        }
        /**
         * 开启事务
         */
        Db::startTrans();
        try{
            //添加用户档案信息
            $res = Db::name('customer_file')->insert(['user_id'=>$post['user_id'],'file_number'=>$post['file_number']]);
            $data['status'] = '立案';
            $res2 = $this->order_operation($post['order_no'],$data,'整理完成');
            if($res && $res2){
                //提交事务
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            /**
             * 事务回滚
             */
            Db::rollback();
            return_json(0,$e->getMessage());
        }

    }

    /**
     * 确认开庭
     * order_no    订单号
     * court_time   开庭时间
     */
    public function hold_court()
    {

        $validate = new Validate([
            'court_time'=>'require',
            'order_no'  => 'require',
        ]);
        $validate->message([
            'court_time.require' => '开庭时间不能为空',
            'order_no.require' => '订单号不能为空',
        ]);

        $post = request()->param();
        if (!$validate->check($post)) {
            return_json(0,$validate->getError());
        }
        $data['court_time'] = $post['court_time'];
        $data['status'] = '等待开庭';
        /**
         * 开启事务
         */
        Db::startTrans();
        try{
            $res = $this->order_operation($post['order_no'],$data,'确认开庭');
            if($res){
                //提交事务
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,'操作失败');
        }

    }


    /**
     * 开庭
     * order_no   订单号
     */
    public function court()
    {
        $order_no = request()->param('order_no');
        $data['status'] = '等待结果';
        Db::startTrans();
        try{
            $res = $this->order_operation($order_no,$data,'开庭');
            if($res){
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,$e->getMessage());
        }
    }


    /**
     * 收到结果
     * order_no   订单号
     */
    public function results_received()
    {
        $order_no = request()->param('order_no');
        $data['status'] = '执行';
        Db::startTrans();
        try{
            $res = $this->order_operation($order_no,$data,'收到结果');
            if($res){
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,$e->getMessage());
        }
    }

    /**
     * 调解
     * order_no   订单号
     */
    public function mediate()
    {
        $order_no = request()->param('order_no');
        $data['status'] = '调解';
        Db::startTrans();
        try{
            $res = $this->order_operation($order_no,$data,'调解');
            if($res){
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,$e->getMessage());
        }
    }


    /**
     * 我方起诉|对方起诉
     * order_no    订单号
     * type       我方起诉|对方起诉
     */
    public function prosecute()
    {
        $validate = new Validate([
            'type'=>'require',
            'order_no'  => 'require',
        ]);
        $validate->message([
            'type.require' => '起诉方不能为空',
            'order_no.require' => '订单号不能为空',
        ]);

        $post = request()->param();
        if (!$validate->check($post)) {
            return_json(0,$validate->getError());
        }
        $data['status'] = $post['type'];
        Db::startTrans();
        try{
            $res = $this->order_operation($post['order_no'],$data,$post['type']);
            if($res){
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,$e->getMessage());
        }
    }


    /**
     * 案件失败
     * order_no    订单号
     * user_id      用户id
     * 逻辑:将父订单改为失败,记录订单操作,更改用户状态
     */
    public function fail()
    {
        $order_no = request()->param('order_no');
        $user_id = request()->param('user_id');
        $data['status'] = '无尾款';
        Db::startTrans();
        try{
            //将用户状态改为失败
            $user_res = Db::name('customer')->where('id',$user_id)->update(['status'=>$data['status']]);
            $res = $this->order_operation($order_no,$data,'失败');
            //插入用户状态操作记录
            $admin_id = session('ADMIN_ID');
            $record_data['admin_id'] = $admin_id;
            $record_data['create_time'] = time();
            $record_data['user_id'] = $user_id;
            $record_data['type_name'] = '失败';
            $record_data['content'] = date('Y-m-d H:i:s').','.$this->admin_name;
            $res1 = Db::name('record')->insert($record_data);
            if($res && $user_res && $res1){
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,$e->getMessage());
        }

    }


    /**
     * 坏账
     * order_no    订单号
     * user_id    用户id
     *
     * 逻辑:将父订单改为坏账,记录订单操作,更改用户状态
     */
    public function bad_debt()
    {
        $order_no = request()->param('order_no');
        $user_id = request()->param('user_id');
        $data['status'] = '坏账';
        Db::startTrans();
        try{
            $user_res = Db::name('customer')->where('id',$user_id)->update(['status'=>$data['status']]);
            $res = $this->order_operation($order_no,$data,'坏账');
            //插入用户状态操作记录
            $admin_id = session('ADMIN_ID');
            $record_data['admin_id'] = $admin_id;
            $record_data['create_time'] = time();
            $record_data['user_id'] = $user_id;
            $record_data['type_name'] = '无尾款';
            $record_data['content'] = date('Y-m-d H:i:s').','.$this->admin_name;
            $res1 = Db::name('record')->insert($record_data);
            if($res && $user_res && $res1){
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,$e->getMessage());
        }

    }

    /**
     * 强制执行
     * order_no    订单号
     */
    public function enforcement()
    {
        $order_no = request()->param('order_no');
        $data['status'] = '强制执行';
        Db::startTrans();
        try{
            $res = $this->order_operation($order_no,$data,'强制执行');
            if($res){
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,$e->getMessage());
        }
    }



    /**
     *退费--总额返回
     * order_no 订单号
     */
    public function refund()
    {
        $order_no = request()->param('order_no');
        $total_money = Db::name('order_son')->where('parent_order',$order_no)->where('order_type',1)->value('pay_money');

        return_json(1,'',$total_money);
    }


    /**
     * 退费提交
     * order_no   订单号
     * money      退款数
     * user_id    用户id
     *
     *逻辑:将用户,父订单,子订单的状态改为退款,以及子订单支付金额减少和订单操作记录
     */
    public function commit_refund()
    {
        $validate = new Validate([
            'money'=>'require',
            'order_no'  => 'require',
        ]);
        $validate->message([
            'money.require' => '退费金额不能为空',
            'order_no.require' => '订单号不能为空',
        ]);

        $post = request()->param();
        if (!$validate->check($post)) {
            return_json(0,$validate->getError());
        }
        $data['status'] = '退费';
        /**
         * 开启事务
         */
        Db::startTrans();
        try{
            //更改用户状态为退款
            $res = Db::name('customer')->where('id',$post['user_id'])->update(['status'=>$data['status']]);
            $pay_money = Db::name('order_son')->where('parent_order',$post['order_no'])->where('order_type',1)->value('pay_money');
            //计算退款后的实际支付金额并更新子订单信息
            $money = $pay_money-$post['money'];
            $res2 = Db::name('order_son')->where('parent_order',$post['order_no'])->where('order_type',1)->update(['status'=>$data['status'],'refund'=>$post['money'],'pay_money'=>$money]);
            //更改父订单状态|插入订单操作记录
            $res3 = $this->order_operation($post['order_no'],$data,'退费');
            //插入用户状态操作记录
            $admin_id = session('ADMIN_ID');
            $record_data['admin_id'] = $admin_id;
            $record_data['create_time'] = time();
            $record_data['user_id'] = $post['user_id'];
            $record_data['type_name'] = '退费';
            $record_data['content'] = date('Y-m-d H:i:s').','.$this->admin_name;
            $res4 = Db::name('record')->insert($record_data);
            if($res && $res2 && $res3 && $res4){
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::rollback();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,$e->getMessage());
        }

    }

    /**
     * 添加尾款订单
     * order_no      订单号
     * indemnity     赔偿总额
     * remind        提点
     * receivables   预付款
     * order_type   订单类型
     * user_id    用户id
     *
     * 逻辑:将用户状态,父订单状态改为案件完结,子订单改为待支付,插入订单操作记录
     */
    public function add_tail()
    {
        $validate = new Validate([
            'indemnity'    =>'require',
            'order_no'     => 'require',
            'remind'       => 'require',
            'receivables'  => 'require',
            'user_id'  => 'require',
        ]);
        $validate->message([
            'indemnity.require' => '赔偿总额不能为空',
            'order_no.require' => '订单号不能为空',
            'remind.require' => '提点不能为空',
            'receivables.require' => '预售款不能为空',
            'user_id.require' => '用户id不能为空',
        ]);
        $post = request()->param();

        if (!$validate->check($post)) {
            return_json(0,$validate->getError());
        }
        /**
         * 开启事务
         */
        Db::startTrans();
        try{
            $data['status'] = '案件完结';
            //拼接子订单数据
            $admin_id = session('ADMIN_ID');
            $son_no = time().rand(1111,9999);   //生成子订单号
            $son_data['parent_order'] = $post['order_no'];
            $son_data['son_no'] = $son_no;
            $son_data['admin_id'] = $admin_id;
            $son_data['order_name'] = $post['order_type'].'尾款';
            $son_data['order_type'] = 2;   //订单类型 1为首款 |２为尾款
            $son_data['payment'] = $post['receivables'];
            $son_data['pay_money'] = $post['receivables'];
            $son_data['status'] = '尾款待支付';
            $son_data['indemnity'] = $post['indemnity'];
            $son_data['receivables'] = $post['receivables'];
            $son_data['remind'] = $post['remind'];
            $son_data['create_time'] = time();
            $res = Db::name('order_son')->insert($son_data);
            //更改用户状态
            $res2 = Db::name('customer')->where('id',$post['user_id'])->update(['status'=>$data['status']]);
            $res3 = $this->order_operation($post['order_no'],$data,'生成尾款订单');
            if($res && $res2 && $res3){
                Db::commit();
                return_json(1,'操作成功');
            }else{
                Db::commit();
                return_json(0,'操作失败');
            }
        }catch (\Exception $e){
            Db::rollback();
            return_json(0,'操作失败');
        }
    }

    /**
     * 律师列表返回
     */
    public function lawyer_list()
    {
        $id = Db::name('role')->where('name','律师')->value('id');
        $ids = Db::name('role_user')->where('role_id',$id)->column('user_id');
        $list = Db::name('user')->where('id','in',$ids)->select();

        return_json(1,'',$list);
    }

    /**
     * 订单操作公共方法(更改订单状态以及添加订单操作状态记录)
     * @param string $order_no     订单号
     * @param array $post          需要修改订单状态的数据
     * @param string $operation    操作
     */
    public function order_operation($order_no='',$post=[],$operation='')
    {
        $post['update_time'] = time();
        $res2 = Db::name('order_operation')->insert([
            'order_no'=>$order_no,
            'admin_id'=>session('ADMIN_ID'),
            'operation'=>$operation,
            'order_status'=>$post['status'],
            'create_time'=>time()
        ]);
        $res1 = Db::name('order')->where('order_no',$order_no)->update($post);
        if($res1 && $res2){
            return true;
        }else{
            return false;
        }
    }


}